﻿using Casamiel.Domain;

using Dapper;
using Smooth.IoC.UnitOfWork.Interfaces;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Casamiel.Infrastructure.Repositories
{
	/// <summary>
	/// 
	/// </summary>
	public sealed  class ErrorLogRepository : BaseRepository<ErrorLog,int>, IErrorLogRepository
	{
		public ErrorLogRepository(IDbFactory factory) : base(factory)
		{
		}


		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="TSession"></typeparam>
		/// <returns></returns>
		public async Task<String> GetHappyLandAppUrlAsnyc<TSession>() where TSession : class, ISession
		{
			string sql = "SELECT  top 1  AppUrl FROM dbo.log_appversion where apptype=5 order by CreateTime desc";
			using var session = Factory.Create<TSession>();
			var list = await session.ExecuteScalarAsync(sql.CheckSafeSql()).ConfigureAwait(false);
			return list.ToString();

		}
        /// <summary>
        /// Gets the list asnyc.
        /// </summary>
        /// <returns>The list asnyc.</returns>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="pageSize">Page size.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
        public async Task<PagingResult<ErrorLog>> GetListAsnyc<TSession>(int pageIndex, int pageSize) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                PagingResult<ErrorLog> result = new PagingResult<ErrorLog>
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
                int total = 0;
                var sql = GetSelectSQL($"{Sql.Table<ErrorLog>(session.SqlDialect)}", $"", "ID desc", pageIndex, pageSize);
                string countsql = $"select count(0) from {Sql.Table<ErrorLog>(session.SqlDialect)}";

                total = await session.Connection.QueryFirstAsync<int>(countsql).ConfigureAwait(false);
                var list = await session.Connection.QueryAsync<ErrorLog>(sql.Item1,new { begin = sql.Item2, end = sql.Item3 }).ConfigureAwait(false);
                result.Data = list.ToList();
                result.Total = total;
                return result;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TSession"></typeparam>
        /// <returns></returns>
        public async Task<String> GetAppDownlaodUrlAsnyc<TSession>(int apptype) where TSession : class, ISession
        {
            string sql = $"SELECT  top 1  AppUrl FROM dbo.log_appversion where apptype={apptype} order by CreateTime desc";
            using var session = Factory.Create<TSession>();
            var list = await session.ExecuteScalarAsync(sql.CheckSafeSql()).ConfigureAwait(false);
            return list.ToString();

        }
    }
}
